package com.optitronics.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.optitronics.beans.Reseller;
import com.optitronics.service.ResellerService;
import com.optitronics.ui.ResellerForm;
import com.optitronics.util.OptitronicsConstants;
import com.optitronics.util.OptitronicsUtils;

@RequestMapping("/resellers")
@Controller
public class ResellerController {

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private GenericConversionService conversionService;

	@Autowired
	private ResellerService resellerService;

	@RequestMapping("/activateRegistration/{resellerEmail}/{activationToken}")
	public String activateRegistration(Model model, @PathVariable("resellerEmail") String resellerEmail,
			@PathVariable("activationToken") String activationToken) {

		boolean activationResult = resellerService.activateRegistration(resellerEmail, activationToken);
		String message = activationResult ? "label.registration.confirmed" : "label.registration.error";
		model.addAttribute("message", message);

		return "infoPage";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String show(@PathVariable("id") Integer id, Model model) {

		Reseller reseller = Reseller.findReseller(id);
		ResellerForm formObj = new ResellerForm(reseller);

		String statusText = messageSource.getMessage("label.reseller.status." + reseller.getStatus(), null,
				LocaleContextHolder.getLocale());
		formObj.setStatusText(statusText);
		model.addAttribute("reseller", formObj);
		model.addAttribute("itemId", id);
		model.addAttribute("update", OptitronicsUtils.isUserAdmin());
		return "resellers/show";
	}

	private List<ResellerForm> getResellerForms(List<Reseller> resellers) {

		List<ResellerForm> results = new ArrayList<ResellerForm>();
		for (Reseller reseller : resellers) {
			ResellerForm formObj = new ResellerForm(reseller);

			String statusText = messageSource.getMessage("label.reseller.status." + reseller.getStatus(), null,
					LocaleContextHolder.getLocale());
			formObj.setStatusText(statusText);
			results.add(formObj);
		}
		return results;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String list(@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size, Model model) {
		if (page != null || size != null) {
			int sizeNo = size == null ? OptitronicsConstants.PAGE_SIZE : size.intValue();
			List<Reseller> resellers = Reseller.findResellerEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo,
					sizeNo);

			model.addAttribute("resellers", getResellerForms(resellers));
			float nrOfPages = (float) Reseller.countResellers() / sizeNo;
			model.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
					: nrOfPages));
		} else {

			List<Reseller> resellers = Reseller.findAllResellers();
			model.addAttribute("resellers", getResellerForms(resellers));
		}
		model.addAttribute("update", true);
		model.addAttribute("size", OptitronicsConstants.PAGE_SIZE);

		return "resellers/list";
	}

	Converter<Reseller, String> getResellerConverter() {
		return new Converter<Reseller, String>() {
			public String convert(Reseller reseller) {
				return new StringBuilder().append(reseller.getVersion()).append(" ").append(reseller.getName())
						.append(" ").append(reseller.getTaxNumber()).toString();
			}
		};
	}

	@PostConstruct
	void registerConverters() {
		conversionService.addConverter(getResellerConverter());
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

}
